import { reqTenantList, reqProductModelPage, reqTerminalTask, reqHistoryExportTask } from "@api/api.js";
import { validImeis } from "@utils/validate";

export default {
    data() {
        return {
            enterpriseList: [],
            classMarkList: [],
            sysInstanceIndex: 1,
            sysInstanceTotalPages: 10,
            loading: false,
            flag: true,
            searchForm: {
                productId: "",
                imeiList: '',
                tenantId: "",
                productModel: "",
                startTime: "",
                endTime: "",
                timeArr: []
            },
            rules: {
                imeiList: [{
                    validator: validImeis
                }],
                tenantId: [
                    { required: true, message: " ", trigger: "change" },
                ],
                productId: [
                    { required: true, message: " ", trigger: "change" },
                ],
                productModel: [
                    { required: true, message: " ", trigger: "change" },
                ],
                timeArr: [
                    { required: true, message: " ", trigger: "change" },
                ],
            },
            // 导出筛选条件
            exportList: {
                productId: "",
                imeiList: "",
                tenantId: "",
                productModel: "",
                startTime: "",
                endTime: ""
            },
            // 日期范围限制为7天 今天之后和前3个月的时间不可选
            pickerOptions: {
                onPick: ({ maxDate, minDate }) => {
                    this.cuttentTime = minDate.getTime();
                    if (maxDate) {
                        this.cuttentTime = "";
                    }
                },
                disabledDate: (time) => {
                    // 获取当前时间
                    const now = new Date();
                    // 限制只能选择今天及之前的日期
                    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
                    const todayTimestamp = today.getTime();

                    // 限制不能选择3个月前的日期
                    const threeMonthsAgo = new Date(now.getFullYear(), now.getMonth() - 3, now.getDate());
                    const threeMonthsAgoTimestamp = threeMonthsAgo.getTime();

                    // 如果已经选择了开始日期
                    if (this.cuttentTime) {
                        // 限制7天范围
                        const sevenDays = 7 * 24 * 3600 * 1000;
                        const minTime = this.cuttentTime;
                        const maxTime = this.cuttentTime + sevenDays;

                        // 返回true表示禁用该日期
                        return time.getTime() > todayTimestamp ||
                            time.getTime() < threeMonthsAgoTimestamp ||
                            (time.getTime() < minTime || time.getTime() > maxTime);
                    } else {
                        // 还没选择开始日期时，只限制不能选择今天之后和3个月前的日期
                        return time.getTime() > todayTimestamp ||
                            time.getTime() < threeMonthsAgoTimestamp;
                    }
                },
            },
        };
    },
    async mounted() {
        this.searchForm.timeArr = [this.getPrevious7thDay(), this.formatDate(new Date())]
        await this.getEnterpriseList(true);
        await this.getProductList(true)
        await this.ProductModelPage(true)
        await this.getDataList();
    },
    methods: {
        getPrevious7thDay() {
            const date = new Date(); // 当前日期
            date.setDate(date.getDate() - 7); // 减去7天

            // 格式化日期为YYYY-MM-DD（可选）
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');

            return `${year}-${month}-${day} 23:59:59`;
        },
        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day} 00:00:00`;
        },
        // 搜索
        async searchClick1() {
            if (this.searchForm.imeiList == '') {
                this.page = 1;
                this.limit = 10;
                this.showPopover = false;
                await this.getDataList();
                return;
            }
            this.$refs.refForm.validate(async(valid) => {
                if (!valid) return;
                this.page = 1;
                this.limit = 10;
                this.showPopover = false;
                await this.getDataList();
            });
        },
        // 高级搜索重置
        async resetClick() {
            this.searchForm.productId = "";
            this.searchForm.manufacturerId = "";
            this.searchForm.tenantId = "";
            this.searchForm.protocol = "";
            this.searchForm.productModel = "";
            this.page = 1;
            this.limit = 10;
            await this.getDataList();
        },
        // 租户
        async loadMore() {
            if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10))
                return;
            this.sysInstanceIndex++;
            this.loading = true;
            // 获取列表数据的方法
            await this.getEnterpriseList();
            this.loading = false;
        },
        // 下拉请求列表
        enterprise(val) {
            if (val && this.flag) {
                this.getEnterpriseList();
                this.flag = false; //只执行一次
            }
        },
        // 获取租户列表
        async getEnterpriseList(flag = false) {
            var res = await reqTenantList(this.sysInstanceIndex, 10);
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.sysInstanceTotalPages = res.data.total;
            this.enterpriseList = [...this.enterpriseList, ...res.data.rows];
            if (this.enterpriseList.length > 0 && flag) {
                this.searchForm.tenantId = this.enterpriseList[0].id
            }
        },
        // 获取产品型号
        async ProductModelPage(e) {
            this.classMarkList = [];
            this.searchForm.productModel = "";
            if (!e) return;
            let res = await reqProductModelPage(1, 30, {
                productId: this.searchForm.productId,
            });
            // console.log(res);
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.classMarkList = res.data.rows;
            if (this.classMarkList.length > 0) {
                this.searchForm.productModel = this.classMarkList[0].model;
            }
        },
        // 导出  设备筛选有几个字段，接口就要加几个字段
        async onExports() {
            if (this.total == 0) return this.$modal.notifyWarning('当前筛选条件没有原始数据可供导出');
            const result = await this.$confirm(
                "此操作将导出设备原始数据, 是否继续?",
                "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            ).catch(() => {});
            if (result !== "confirm") return;
            const res = await reqHistoryExportTask(this.exportList);
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.$modal.notifySuccess("导出成功，请在任务管理中查看");
            this.$router.push({ name: "exportTask" });
        },
    },
};